<template>
  <div id="app">
    <div style="display: flex;">
      <div style="width: 250px;height: 300px ;border: 1px solid black;">
        <el-tree :data="formattedTreeData" accordion v-model="selectLocation" @node-click="handleNodeClick"></el-tree>
      </div>
      <div style="margin-left: 20px;">
        用户名称 <el-input v-model="selectUserName" placeholder="请输入用户名称" style="width: 200px;" clearable></el-input>
        手机号码 <el-input v-model="selectPhone" placeholder="请输入手机号码" style="width: 200px;" clearable></el-input>
        状态 <el-select v-model="selectStatus" style="width: 200px;" clearable>
          <el-option label="启用" value="1">启用</el-option>
          <el-option label="禁用" value="0">禁用</el-option>
        </el-select><br>
        <br>
        创建时间 <el-date-picker v-model="value1" type="daterange" range-separator="-" start-placeholder="开始日期"
          end-placeholder="结束日期" clearable>
        </el-date-picker>
        <el-button type="primary" style="height: 35px;" @click.native="getSysUserList(1)">
          <i class="el-icon-search">搜索</i></el-button>
        <el-button style="height: 35px;" @click="reset"><i class="el-icon-refresh">重置</i></el-button>
        <br>
        <br>
        <el-button type="primary" style="height: 32px;" @click.native="addUserValue"><i
            class="el-icon-plus">新增</i></el-button>
      </div>
    </div>
    <div style="position: absolute;left: 300px;top: 200px;">
      <el-table ref="multipleTable" :data="sysUserList" tooltip-effect="dark" style="width: 100%"
        @selection-change="handleSelectionChange">
        <!-- <el-table-column type="selection" width="55">
        </el-table-column> -->
        <el-table-column type="id" label="用户编号" width="150">
          <template slot-scope="scope">{{ scope.row.id }}</template>
        </el-table-column>
        <el-table-column type="username" label="用户名称" width="150">
          <template slot-scope="scope">{{ scope.row.username }}</template>
        </el-table-column>
        <el-table-column type="deptName" label="部门" width="150">
          <template slot-scope="scope">{{ scope.row.deptName }}</template>
        </el-table-column>
        <el-table-column type="phone" label="手机号码" width="150">
          <template slot-scope="scope">{{ scope.row.phone }}</template>
        </el-table-column>
        <el-table-column type="status" label="状态" width="150">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.status" @click.native="updateStatus(scope.row)" active-color="#13ce66" inactive-color="#ff4949" active-value="1"
              inactive-value="0">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column type="createTime" prop="name" label="创建时间" width="160">
          <template slot-scope="scope">{{ scope.row.createTime }}</template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="150">
          <template slot-scope="scope">
            <el-tooltip effect="dark" content="编辑" placement="top">
              <el-button type="primary" icon="el-icon-edit" size="mini" circle @click="upd(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="删除" placement="top">
              <el-button type="danger" icon="el-icon-delete" size="mini" circle @click="del(scope.row.id)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-top: 30px;margin-left: 870px;" v-if="pageCount >= 1">
        <el-button-group>
          <el-button type="primary" icon="el-icon-arrow-left" @click="prevPage">上一页</el-button>
          <el-button><span>{{ pageNum }} / {{ pageCount }}</span></el-button>
          <el-button type="primary" @click="nextPage">下一页<i class="el-icon-arrow-right el-icon--right"></i></el-button>
        </el-button-group>
      </div>
    </div>


    <el-row v-if="addUserShow">
      <el-dialog title="用户信息" :visible.sync="addUserShow" width="38%">
        <el-form :inline="true" :rules="rules" ref="form" :model="form" class="demo-form-inline">
          <el-form-item label="用户名称" prop="username">
            <el-input v-model="form.username" style="width: 200px;"></el-input>
          </el-form-item>
          <el-form-item label="归属部门" prop="deptId">
            <el-cascader v-model="form.deptId" :options="formattedTreeData" :props="{ checkStrictly: true }" clearable
              @change="handleCascaderChange">
            </el-cascader>
          </el-form-item>
          <el-form-item label="手机号码" prop="phone">
            <el-input v-model="form.phone" style="width: 200px;"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="form.email" style="width: 200px;"></el-input>
          </el-form-item>
          <el-form-item label="用户密码" prop="password">
            <el-input type="password" v-model="form.password" style="width: 200px;"></el-input>
          </el-form-item>
          <el-form-item label="用户性别" prop="sex">
            <el-select v-model="form.sex" style="width: 200px;height: 30px;">
              <el-option label="男" value="0">男</el-option>
              <el-option label="女" value="1">女</el-option>
              <el-option label="未知" value="2">未知</el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="form.status" style="width: 200px;" clearable>
              <el-option label="启用" value="1">启用</el-option>
              <el-option label="禁用" value="0">禁用</el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="角色" prop="role">
            <el-select v-model="form.roleIds" style="width: 200px;height: 30px;" @click.native="getListAll">
              <el-option v-for="item in sysRoleList" :key="item.id" :label="item.name" :value="item.id">{{ item.name
                }}</el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="备注" prop="note">
            <el-input type="textarea" v-model="form.note" style="width: 500px;"></el-input>
          </el-form-item>
        </el-form>
        <div style="display: flex;gap: 10px;position: absolute;right: 20px;bottom: 0;height: 50px;">
          <span slot="footer" class="dialog-footer">
            <el-button type="primary" v-if="userShow==0" @click="add('form')">添加</el-button>
            <el-button type="primary" v-if="userShow==1" @click="updUser('form')">修改</el-button>
            <el-button @click="addUserShow = false">取 消</el-button>
          </span>
        </div>
      </el-dialog>
    </el-row>
  </div>
</template>

<script>
import axios from 'axios';
export default {
    name: 'app',
    data() {
      return {
        selectUserName: '',
        selectPhone:'',
        selectStatus:'',
        selectLocation:'',
        value1: '',
        userShow:'',
        addUserShow:false,
        id:'',
        form:{},
        rules: {
          username: [
            { required: true, message: '请输入用户名称', trigger: 'blur' },
          ],
          deptId: [
            { required: true, message: '请选择所属部门', trigger: 'blur' },
          ],
          phone: [
            { required: true, message: '请输入手机号码', trigger: 'blur' },
            { min: 11, max: 11, message: '长度为11位', trigger: 'blur' }
          ],
          email: [
            { required: true, message: '请输入邮箱', trigger: 'blur' },
          ],
          password: [
            { required: true, message: '请输入用户密码', trigger: 'blur' },
            { min: 6, message: '密码长度最低6个字符', trigger: 'blur' }
          ],
        },
        pageNum:1,
        pageSize:10,
        pageCount:'',
        
        sysUserList:[],
        beginTime:'',
        endTime:'',
        //部门
        sysDeptList:[],
        pid:'',
        deptId:'',
        //角色
        sysRoleList:[]
      }
    },
    created(){
      this.getSysUserList(1);
      this.getDeptList();
    },
    computed: {
      formattedTreeData() {
        const data = this.sysDeptList;
        console.log(this.sysDeptList);
        function processData(data, pid = 0, level = 0) {
          const result = [];
          data.forEach(item => {
            if (item.pid === pid) {
              const node = {
                label: item.name,
                value: item.id,
                children: level <1 ?  processData(data, item.id, level + 1):null
              };
              result.push(node);
            }
          });
          return result;
        }
        return processData(data);
      },
    },
    methods: {
      prevPage() {
            this.pageNum--;
            var pageNum = this.pageNum;
            if (this.pageNum >= 1) {
                this.getSysUserList(pageNum);
            } else {
                this.getSysUserList(1);
            }
        },
        nextPage() {
            this.pageNum++;
            var pageNum = this.pageNum;
            if (this.pageNum <= this.pageCount) {
                this.getSysUserList(pageNum);
            } else {
                this.getSysUserList(this.pageCount);
            }
        },
      handleNodeClick(data) {
        this.selectLocationJoin = data.value;
        console.log(this.selectLocationJoin);
        this.getSysUserList(1);
      },
      getDeptList(){
        let Authorization = localStorage.getItem("Authorization");
        axios({
          url: 'http://localhost:9002/sys/dept/list',
          method: 'get',
          headers: {
            'Authorization': Authorization
          }
        })
        .then(response => {
          this.sysDeptList = response.data.data;
        })
      },
      getSysUserList(pageNum){
        this.pageNum = pageNum;
        if (this.value1.length === 2) {
          const beginTime = this.value1[0];
          const endTime = this.value1[1];
          this.beginTime = beginTime;
          this.endTime = endTime;
          console.log('开始时间:', beginTime);
          console.log('结束时间:', endTime);
        }
        let Authorization = localStorage.getItem("Authorization");
        axios({
          url: 'http://localhost:9002/sys/user/list',
          method: 'get',
          params: {
            pageNum: this.pageNum,
            pageSize: 10,
            username: this.selectUserName,
            phone: this.selectPhone,
            status: this.selectStatus,
            deptId: this.selectLocationJoin,
            beginTime: this.beginTime,
            endTime: this.endTime
          },
          headers: {
            'Authorization': Authorization
          }
        })
        .then(response => {
          console.log(response);
          this.sysUserList = response.data.data.list;
          this.pageCount = response.data.data.totalPage;
          console.log(this.sysUserList);
        })
      },
      addUserValue(){
        this.form = {};
        this.userShow = 0;
        this.addUserShow = true;
      },
      getListAll(){
        let Authorization = localStorage.getItem("Authorization");
        axios({
          url: 'http://localhost:9002/sys/role/listAll',
          method: 'get',
          headers: {
            'Authorization': Authorization
          }
        })
        .then(response => {
          console.log(response);
          this.sysRoleList = response.data.data;
        })
      },
      handleCascaderChange(selectedNodes) {
        console.log('Selected Nodes:', selectedNodes);
        // 只获取选中的最后一个节点数据
        const selectedData = selectedNodes[selectedNodes.length - 1];
        console.log('Selected Data:', selectedData);
        this.form.deptId = selectedData;
      },
      add(formName){
        this.$refs[formName].validate((valid) => {
          if (valid) {
            console.log(this.form);
            let aa;
            if(this.form.roleIds != ''){
              aa = [this.form.roleIds];
            }
            if(this.form.status==''){
              this.form.status=0;
            }
            let Authorization = localStorage.getItem("Authorization");
            axios({
              url: 'http://localhost:9002/sys/user/create',
              method: 'post',
              data: {
                username: this.form.username,
                deptId: Number(this.form.deptId),
                deptName: this.form.deptName,
                phone: this.form.phone,
                email: this.form.email,
                password: this.form.password,
                sex: this.form.sex,
                status: this.form.status,
                roleIds: aa,
                note: this.form.note
              },
              headers: {
                'Authorization': Authorization,
                'Content-Type': 'application/json'
              }
            })
            .then(response => {
              console.log(response);
              if(response.data.code == 200){
                this.$message.success('添加成功');
                this.addUserShow = false;
                this.getSysUserList(1);
              }else{
                this.$message.error('添加失败');
              }
            })
          }else {
            return false;
          }
        })
      },
      reset(){
        this.selectUserName='';
        this.selectPhone='';
        this.selectStatus='';
        this.value1='';
        this.beginTime='';
        this.endTime='';
        this.getSysUserList(1);
      },
      upd(row){
        let Authorization = localStorage.getItem("Authorization");
        this.userShow = 1;
        
        axios({
          url: `http://localhost:9002/sys/user/info/${row.id}`,
          method: 'get',
          headers: {
            'Authorization': Authorization
          }
        })
        .then(response => {
          let row = response.data.data;
          this.form = row;
          if(row.roleIds != ''){
            this.form.roleIds = row.roleIds[0];
          }
          console.log(row.roleIds);
          console.log(this.form.roleIds);
        })
        this.id = row.id;
        this.addUserShow = true;
      },
      updateStatus(row){
        if (confirm("确定要修改状态吗？")) {
          let status;
          if (row.status == 0) {
            status = '0';
          } else if (row.status == 1) {
            status = '1';
          }
          let Authorization = localStorage.getItem("Authorization");
          axios({
            url: `http://localhost:9002/sys/user/update/status/${row.id}`,
            method: 'put',
            params: {
              status: status
            },
            headers: {
              'Authorization': Authorization
            }
          })
            .then(response => {
                console.log(response);
                if(response.data.code == 200){
                  this.$message.success('修改成功');
                  this.getSysUserList(1);
                }else{
                  this.$message.error('修改失败');
                }
            })
        }
      },
      updUser(formName){
        this.$refs[formName].validate((valid) => {
          if (valid) {
            console.log(this.form);
            console.log(this.id);
            let aa;
            if(this.form.roleIds != ''){
              aa = [this.form.roleIds];
            }
            if(this.form.status==''){
              this.form.status=0;
            }
            let Authorization = localStorage.getItem("Authorization");
            axios({
              url: `http://localhost:9002/sys/user/update/${this.id}`,
              method: 'put',
              data: {
                id: this.id,
                username: this.form.username,
                deptId: Number(this.form.deptId),
                deptName: this.form.deptName,
                phone: this.form.phone,
                email: this.form.email,
                password: this.form.password,
                sex: this.form.sex,
                status: this.form.status,
                roleIds: aa,
                note: this.form.note
              },
              headers: {
                'Authorization': Authorization,
                'Content-Type': 'application/json'
              }
            })
            .then(response => {
              console.log(response);
              if(response.data.code == 200){
                this.$message.success('修改成功');
                this.addUserShow = false;
                this.getSysUserList(1);
              }else{
                this.$message.error('修改失败');
              }
            })
          }else {
            return false;
          }
        })
      },
    }
}
</script>
